import { defineStore } from "pinia";
import { v4 as uuidv4 } from "uuid";

export const useUserStore = defineStore("userStore", {
  state: () => {
    return {
      userList: [],
    };
  },
  getters: {
    getUserList: (state) => state.userList,
  },
  actions: {
    async fetchUser() {
      const { data } = await useFetch("/api/users");
      this.userList = data;
    },
    async getUserById(id) {
      // return this.userList.find((item) => item.id === id);
      const { data } = await useFetch(`/api/users/${id}`);
      return data.value;
    },
    async editUserById(id, user) {
      // 更新远程仓库
      await $fetch(`/api/users/${id}`, {
        method: "PUT",
        body: JSON.stringify(user),
        headers: {
          "Content-Type": "application/json",
        },
      });
      // 更新本地数据
      const index = this.userList.findIndex((item) => item.id === id);
      this.userList[index] = user;
    },
    async addUser(user) {
      // 更新远程仓库
      const newUser = await $fetch("/api/users", {
        method: "POST",
        body: JSON.stringify(user),
        headers: {
          "Content-Type": "application/json",
        },
      });
      // 更新本地数据
      this.userList.push(newUser);
    },
    async deleteUserById(id) {
      await $fetch(`/api/users/${id}`, {
        method: "DELETE",
      });
      // const index = this.userList.findIndex((item) => item.id === id);
      // this.userList.splice(index, 1);
      this.userList = this.userList.filter((item) => item.id !== id);
    },
  },
});
